<?php
/*
 * Created on Apr 2, 2006
 *
 * Helper functions for mysql queries.
 */

 /**
 * Function to connect to mysql.
 * Returns the sql link.
 */
function get_mysql_link() {
	global $CONFIG;
 	$mysql_link = mysql_connect($CONFIG['hostname'], $CONFIG['login'], $CONFIG['password']);
		
	if ($mysql_link) {
		mysql_select_db($CONFIG['database'], $mysql_link)
			or die("Couldn't use" . $CONFIG['database'] . mysql_error());
	}
	else {
		die("Could not connect: " . mysql_error());
	}	
	
	return $mysql_link;
}


 /**
  * Insert data safely
  */
function mysql_input($input, $force_int = false) {
	if (is_numeric($input))
		return $input;

        if (!is_string($input)) {
            die(print_r(debug_backtrace(), true));
        }
		
	else if($force_int)
		die("Invalid data, expected integer");
		
	else {
		if (get_magic_quotes_gpc()) {
			//if magic quotes is enabled, remove slashes
			$input = stripslashes($input);
		}
		
		//Make string safe for insert
		$input = mysql_real_escape_string($input);
		
		return $input;
	}
}

/**
 * Function to get a column of results as an array.
 * If which column is not specified, the first one is used.
 */
function column_as_array($result, $column = null) {
	if (!$result)
		die ("Sending query to server failed. DB error: " . mysql_error());
		
	$array = Array();
	
	if (!$column) {
		while ($row = mysql_fetch_array($result)) {
			$array[] = $row[0];
		}
	}
	else {
		while ($row = mysql_fetch_row($result)) {
			$array[] = $row[$column];
		}	
	}
	#stripslashes($array);
	
	return $array;
	
}

function get_results($query) {
	$result = mysql_query($query);
		
		if (!$result)
			die ("Could not send query to DB: " . mysql_error());
			
	$data = array();
	while ($row = mysql_fetch_assoc($result))
		$data[] = $row;
	
	#stripslashes($data);
	
	return $data;
}

function get_single_result($query) {
	$result = mysql_query($query);
	
	if (!$result) {
		die ("Could not send query to DB: " . mysql_error()
                   .  print_r(debug_backtrace(), true));
            }
	
	$row = mysql_fetch_array($result);
	
	return $row;
}
?>
